const { ccclass, property } = cc._decorator;
import FormStopEvent from './FormStopEvent';
import WinNodeBase from './WinNodeBase';

@ccclass
export default class WinFormBase extends cc.Component {
    @property
    formIndex: number = 1;
    @property(cc.Node)
    bgNode: cc.Node = null;
    @property(cc.Node)
    mainNode: cc.Node = null;
    @property
    scaleSize: number = 0.5;
    @property
    pauseScene: boolean = false;//是否暂停场景
    @property
    isBgClose: boolean = false;//点击背景是否触发关闭
    CloseEvents: Array<cc.Component.EventHandler> = [];

    _WinNodeBase: WinNodeBase = null;
    onLoad() {
        this.mainNode.active = true;
        this.mainNode.scale = this.scaleSize
        this.mainNode.opacity = 0;
        this._WinNodeBase = this.mainNode.getComponent(WinNodeBase);
        this._WinNodeBase.init();
        if (!this.bgNode) {
            this.bgNode = this._WinNodeBase.FormBg;
        }
        if (this.isBgClose)
            this.bgNode.on(cc.Node.EventType.TOUCH_START, this.onBgClose, this);
        this.mainNode.on("mainClose", this.onMainClose, this);
        this.onShow();
    }
    onMainClose(event: cc.Event.EventCustom) {
        event.stopPropagation();
        this.onBgClose();
    }
    onBgClose() {
        if (this.pauseScene)
            cc.director.resume();
        let self = this;
        cc.Component.EventHandler.emitEvents(this.CloseEvents, {
            target: this,
            formNode: this.mainNode
        });
        cc.tween(this.mainNode)
            .to(0.2, { scale: this.scaleSize, opacity: 100 })
            .call(() => {
                if (self.formIndex == 1) {
                    self.bgNode.active = false;
                }
                self.mainNode.active = false;
                self.node.destroy();
            }).start();
    }
    onShow() {
        let self = this;
        this._WinNodeBase.isclose = false;
        let control = this.mainNode.getComponent(FormStopEvent);
        if (!control)
            this.mainNode.addComponent(FormStopEvent)
        cc.tween(this.mainNode)
            .to(0.3, { scale: 1, opacity: 255 })
            .call(() => {
                if (self.formIndex == 1) {
                    self.bgNode.active = true;
                }
                self.mainNode.active = true;
                if (self.pauseScene)
                    cc.director.pause();
            }).start();
    }
}
